/*******************************************************************************
 * Copyright (c) 2009 Kevin Bierhoff and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Kevin Bierhoff - initial API and implementation
 *******************************************************************************/
package com.googlecode.twelfdevtools.util;

import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
import org.eclipse.core.filebuffers.ITextFileBufferManager;
import org.eclipse.core.filebuffers.LocationKind;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;

public class BufferUtil {
	
	public interface BufferAction<T> {
		public T bufferAction(IFile f, ITextFileBuffer buffer);
	}

	public static <T> T doInBuffer(IFile f, BufferAction<T> action) throws CoreException {
		final IPath path = f.getFullPath();
		
		ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
		manager.connect(path, LocationKind.IFILE, null);

		try {
			ITextFileBuffer buffer = manager.getTextFileBuffer(path, LocationKind.IFILE);
			return action.bufferAction(f, buffer);
		} 
		finally {
			try {		
				manager.disconnect(path, LocationKind.IFILE, null);
			} 
			catch (CoreException ex) {
				ex.printStackTrace();
			}
		}
	}

}
